package com.clusterswisdom.horn.api.tmall.action.refund;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.clusterswisdom.horn.api.tmall.util.TmallUtil;
import com.taobao.api.FileItem;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.domain.Refund;
import com.taobao.api.domain.RefundMappingResult;
import com.taobao.api.response.LogisticsAddressSearchResponse;
import com.taobao.api.response.RefundGetResponse;
import com.taobao.api.response.RpRefundsAgreeResponse;

public class ConfirmTRefundAction extends AbstractTmallAction implements HornAction {
	
	public static final String REASE = "七天无理由退换货";
	
	private Logger log = LoggerFactory.getLogger(ConfirmTRefundAction.class);

	@Override
	public HornResponse execute(ApiConfig config, JSONObject param) throws Exception {
		Refund ref = getRefund(param);
		param.put("refund_version", ref.getRefundVersion());
		param.put("refund_phase", ref.getRefundPhase());
		
		TaobaoResponse response = null;
		if("Y".equals(param.getString("refundRes"))){
			if (needRefundGod(ref)) {
				LogisticsAddressSearchResponse addr = (LogisticsAddressSearchResponse)TmallInstance.getInstance().executeRequest(new JSONObject(), "logistics", "addressSearch");
				param.put("seller_address_id", addr.getAddresses().get(0).getAreaId());
				param.put("remark", "没有问题，同意退货");
				TmallInstance.getInstance().executeRequest(param, "refund", "rpReturngoodsAgree");
			}
			
			reviewRefund(param);
			response = (RpRefundsAgreeResponse )agreeRefund(param, ref);
			 
			List<RefundMappingResult> results = ((RpRefundsAgreeResponse)response).getResults();
			String resultContent = "";
			for (RefundMappingResult refundMappingResult : results) {
				resultContent += refundMappingResult.getRefundId() + "," + refundMappingResult.getMessage() + "," + refundMappingResult.getSucc() + ";";
			}
			
			log.debug("agree response " + resultContent);
			
		}else{
			response = refuseRefund(config, param);
			
		}
		
//		if (!response.isSuccess()) {
//			return getUnsuccessResponse(response);
//			
//		} else {
//			return new HornResponse(true, "成功");
//			
//		}
		return new HornResponse(true,response);
	}
	
	//通过taobao接口查询相关信息
	protected Refund getRefund(JSONObject param) throws Exception{
		RefundGetResponse resp = (RefundGetResponse) TmallInstance.getInstance().executeRequest(param, "refund", "refundGet");
		return resp.getRefund();
	}
	
	/**
	 * 同意退款
	 * @param param
	 * @param config
	 * @return
	 * @throws Exception 
	 */
	protected TaobaoResponse agreeRefund(JSONObject param, Refund refund) throws Exception {
		String order = param.getString("refund_id")+ "|";
		order += (int)(Double.parseDouble(refund.getRefundFee()) * 100) + "|";	//订单金额
		order += refund.getRefundVersion() + "|";	//退款最后更新时间戳
		order += "onsale";	//退款阶段，固定
		param.put("refund_infos", order);
		
		TaobaoResponse response = TmallInstance.getInstance().executeRequest(param, "refund", "rpRefundsAgree");
		return response;
	}

	/**
	 * 拒绝退款
	 * @param param
	 * @return
	 * @throws Exception 
	 */
	private TaobaoResponse refuseRefund(ApiConfig config, JSONObject param) throws Exception{
		param.put("refuse_proof", getRefundProof(param));
		TaobaoResponse response = TmallInstance.getInstance().executeRequest(param, "refund", "refundRefuse");
		log.debug("refuseRefund " + response.getBody() + "," + response.getMsg() + "," + response.getParams());
		return response;
	}
	
	private TaobaoResponse reviewRefund(JSONObject param) throws Exception {
		return TmallInstance.getInstance().executeRequest(param, "refund", "rpRefundReview");
	}
	
	private FileItem getRefundProof(JSONObject param) throws IOException {
		String proofUrl = (String)param.get("refuse_proof");
		if (proofUrl == null) {
			return null;
			
		} else {
			return TmallUtil.getFileItem(proofUrl);
			
		}
	}
	
	private boolean needRefundGod(Refund refund) {
		return (refund.getHasGoodReturn() != null && refund.getHasGoodReturn().booleanValue());
	}
}